package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.domain.vo.ProjectGroupDeviceResultVO;
import com.ruoyi.system.domain.vo.ProjectGroupParamVO;
import com.ruoyi.system.service.IProjectAuthorizeService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.system.service.ISysUserService;
import io.swagger.models.auth.In;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.ProjectDeviceGroup;
import com.ruoyi.system.service.IProjectDeviceGroupService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.system.domain.ValidationGroups.*;

import javax.validation.constraints.NotNull;

/**
 * 产品分组Controller
 *
 * @author ruoyi
 * @date 2021-08-10
 */
@RestController
@RequestMapping("/system/project_group")
public class ProjectDeviceGroupController extends BaseController {
    @Autowired
    private IProjectDeviceGroupService projectDeviceGroupService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private IProjectAuthorizeService projectAuthorizeService;
    @Autowired
    private ISysUserService sysUserService;


    /**
     * 查询产品分组列表
     */
    @PreAuthorize("@ss.hasPermi('system:project:group:list')")
    @GetMapping("/list")
    public TableDataInfo list(@Validated(Select.class) ProjectDeviceGroup projectDeviceGroup) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        boolean commonRoleFlag = sysUserService.checkUserIsCommonRole(loginUser.getUser());
        if (!commonRoleFlag){
            //TODO 验证当前用户是否授权该项目
            projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectDeviceGroup.getProjectId());
        }
        startPage();
        List<ProjectDeviceGroup> list = projectDeviceGroupService.selectTblProjectDeviceGroupList(projectDeviceGroup);
        return getDataTable(list);
    }

    /**
     * 导出产品分组列表
     */
    @PreAuthorize("@ss.hasPermi('system:group:export')")
    @Log(title = "产品分组", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ProjectDeviceGroup projectDeviceGroup) {
        List<ProjectDeviceGroup> list = projectDeviceGroupService.selectTblProjectDeviceGroupList(projectDeviceGroup);
        ExcelUtil<ProjectDeviceGroup> util = new ExcelUtil<ProjectDeviceGroup>(ProjectDeviceGroup.class);
        return util.exportExcel(list, "产品分组数据");
    }

    /**
     * 获取产品分组详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:project:group:query')")
    @GetMapping(value = "/getInfo")
    public AjaxResult getInfo(Integer id) {
        ProjectDeviceGroup projectDeviceGroup = projectDeviceGroupService.selectTblProjectDeviceGroupById(id);
        if (projectDeviceGroup != null){
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectDeviceGroup.getProjectId());
        }
        return AjaxResult.success(projectDeviceGroupService.selectTblProjectDeviceGroupById(id));
    }

    /**
     * 新增产品分组
     */
    @PreAuthorize("@ss.hasPermi('system:project:group:add')")
    @Log(title = "产品分组", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody @Validated(Create.class) ProjectDeviceGroup projectDeviceGroup) {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        //TODO 验证当前用户是否授权该项目
        projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectDeviceGroup.getProjectId());
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        projectDeviceGroup.setCompanyId(companyId);
        projectDeviceGroup.setCreateBy(loginUser.getUsername());
        projectDeviceGroup.setCreateTime(new Date());
        Boolean flag = projectDeviceGroupService.saveProjectDeviceGroup(projectDeviceGroup);
        if (flag){
            return AjaxResult.success("添加成功");
        }
        return AjaxResult.error("添加失败");
    }

    /**
     * 修改产品分组
     */
    @PreAuthorize("@ss.hasPermi('system:project:group:edit')")
    @Log(title = "产品分组", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated(Update.class) ProjectDeviceGroup projectDeviceGroup) {
        //TODO 验证当前用户是否授权该项目
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectDeviceGroup.getProjectId());
        if(projectDeviceGroupService.updateProjectDeviceGroup(projectDeviceGroup)){
            return AjaxResult.success("修改成功");
        }
        return AjaxResult.error("修改失败");
    }

    @PreAuthorize("@ss.hasPermi('system:project:group:bindDevice')")
    @PostMapping("/bindDevice")
    public AjaxResult bindDevice(@RequestBody ProjectDeviceGroup projectDeviceGroup){
        //LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        //projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectDeviceGroup.getProjectId());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 设置companyId
        Long companyId = sysDeptService.selectCompanyIdByUser(loginUser.getUser());
        projectDeviceGroup.setCompanyId(companyId);
        projectDeviceGroupService.bindDevice(projectDeviceGroup);
        return AjaxResult.success("绑定成功！");
    }

    /**
     * 删除产品分组
     */
    @PreAuthorize("@ss.hasPermi('system:project:group:remove')")
    @Log(title = "产品分组", businessType = BusinessType.DELETE)
    @DeleteMapping("/{id}")
    public AjaxResult remove(@PathVariable @NotNull(message = "id不能为null") Integer id) {
        ProjectDeviceGroup projectDeviceGroup = projectDeviceGroupService.selectTblProjectDeviceGroupById(id);
        if (projectDeviceGroup != null){
            //TODO 验证当前用户是否授权该项目
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectDeviceGroup.getProjectId());
        }
        projectDeviceGroupService.deleteProjectDeviceGroupById(id);
        return AjaxResult.success("删除成功");
    }

    /**
     * 查询需要绑定的产品信息
     * @param projectGroupParamVO
     * @return
     */
    @PreAuthorize("@ss.hasPermi('system:project:group:queryBindDevice')")
    @GetMapping("/queryBindDevice")
    public AjaxResult queryBindDevice(@Validated(Select.class) ProjectGroupParamVO projectGroupParamVO){
        if (projectGroupParamVO != null){
            //TODO 验证当前用户是否授权该项目
            LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
            projectAuthorizeService.checkProjectIsAuthorizeWithProjectId(loginUser.getUser(),projectGroupParamVO.getProjectId());
        }
        ProjectGroupDeviceResultVO projectGroupDeviceResultVO = projectDeviceGroupService.queryBindDevice(projectGroupParamVO);
        return AjaxResult.success(projectGroupDeviceResultVO);
    }

}
